import { useState, useRef, useEffect } from 'react';
import { useAppDispatch } from '@/hook/useRedux';
import { addFileTask, changeTaskDate, pinnedTask, removeTaskItem, renameTask, setPriority, toggleStatusTask } from '@/redux/tasks/tasksSlice';
import { ActionElement, ActionElementComponent } from '@/components/AdvancedButton/AdvancedButtonWrapper';
import { AdvancedButton, AdvancedButtonProps } from '@/components/AdvancedButton/AdvancedButton';
import { DatePicker } from '@/components/DatePicker/DatePicker';
import { PrioritySelectActionMenu } from '@/components/ActionMenu/PrioritySelectActionMenu';

interface useTaskCardProps {
  cardData: Task
}

export const useTaskCard = ({ cardData }: useTaskCardProps) => {
  const [data] = useState(cardData);
  const [showComments, setShowComments] = useState(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [newTaskCard, setNewTaskCard] = useState(false);
  const [removeTask, setRemoveTask] = useState(false);

  const dispatch = useAppDispatch();
  const taskName = useRef<HTMLHeadingElement>(null);

  const removeTaskCard = () => {
    dispatch(removeTaskItem({ id: +cardData.id, columnId: cardData.column_id }));
    setRemoveTask(false);
  };

  const sendFiles = async (uploadFiles: File[]) => {
    let formDataFiles = new FormData();
    formDataFiles.append('task_id', `${data.id}`);
    uploadFiles.forEach((file, i: number) => {
      formDataFiles.append(`files[${i}]`, file);
    });
    formDataFiles.append('gid', `${data.files_gid || ''}`);
    dispatch(addFileTask({ file: formDataFiles, taskId: data.id, colId: data.column_id }));
  };

  const [toggleShow, setToggleShow] = useState<boolean>(() => {
    if (!!cardData.subtaskOpen) {
      return true;
    } else {
      return newTaskCard ? true : false;
    }
  });

  const handleToggle = () => {
    const newToggleShow = !toggleShow;
    setToggleShow(newToggleShow);

    if (toggleShow && newTaskCard) setNewTaskCard(false);
  };

  const onTaskSaveName = (e: React.ChangeEvent<HTMLHeadingElement>, taskId: number) => {
    dispatch(renameTask({ name: e.target.innerText, taskId }));
  };

  const updateTaskPriority = (value: number) => {
    dispatch(setPriority({ taskId: cardData.id, columnId: cardData.column_id, priority: value }))
  }

  const updateTaskPinned = (pinned: 0 | 1) => {
    if (!cardData.is_closed) {
      dispatch(pinnedTask({ pinned: pinned, columnId: cardData.column_id, taskId: cardData.id }))
    }
  }

  const updateTaskIsClosed = (e: any) => {
    e.stopPropagation();
    const isChecked = cardData.is_closed === 1 ? 0 : 1
    dispatch(toggleStatusTask({
      status: isChecked,
      colId: cardData.column_id,
      taskId: cardData.id
    }))


  }

  const handleEditableTaskName = (e: any) => {
    e.stopPropagation();
    setIsEdit(true);
    if (taskName.current) {
      taskName.current.contentEditable = 'true';
      taskName?.current?.focus();
      const range = document.createRange();
      const selection = window.getSelection();
      range.selectNodeContents(taskName.current);
      range.collapse(false);
      selection?.removeAllRanges();
      selection?.addRange(range);
    }
  };

  const taskNameSave = (e: React.ChangeEvent<HTMLHeadingElement>, taskId: number) => {
    onTaskSaveName(e, taskId);
    setIsEdit(false);
  };

  const enterKeyDown = (e: React.KeyboardEvent<HTMLHeadingElement>, taskId: number) => {
    if (e.key === 'Enter') {
      // @ts-ignore:next-line
      taskNameSave(e, taskId);
    }
  };

  const taskCardOptionsAdditional: AdvancedButtonProps = {
    className: `group-hover/taskCard:text-[--btn-color-hover]`,
  };

  const taskCardOptions: AdvancedButtonProps[] = [
    {
      icon: cardData.pinned ? 'Unpin' : 'Pin',
      onClick: (e) => {
        e.stopPropagation();
        updateTaskPinned(cardData.pinned);
      },
      ...taskCardOptionsAdditional,
      className: `ml-auto group-hover/taskCard:text-[--btn-color-hover] `,
    },
    {
      icon: 'Plus',
      onClick: (e) => {
        e.stopPropagation();
        setNewTaskCard(true);
      },
      ...taskCardOptionsAdditional,
    },
  ];

  const actionsInMenuAdditional: AdvancedButtonProps = {
    variant: 'accent',
    className: 'w-full justify-start py-2 pr-3 h-auto',
  };

  const changeEndDate = (date: any) => {
    dispatch(changeTaskDate({ columnId: cardData.column_id, taskId: cardData.id, date: date.end_date }))
  }

  const actionInMenuWrappers: ActionElement[] = [
    {
      element: <ActionElementComponent element={
        <AdvancedButton icon='Pin' {...actionsInMenuAdditional} >
          Закрепить
        </AdvancedButton>} />,
      showActionMenu: false
    },
    {
      element: <ActionElementComponent element={
        <PrioritySelectActionMenu value={Number(cardData.priority_id)} getValue={updateTaskPriority}>
          <AdvancedButton icon='Fire' variant={'accent'} {...actionsInMenuAdditional} >
            Приоритет
          </AdvancedButton>
        </PrioritySelectActionMenu>} />,
    },
    {
      element: <ActionElementComponent element={
        <AdvancedButton icon='User'  {...actionsInMenuAdditional} >
          Добавить исполнителя
        </AdvancedButton>} />
    },
    {
      element: <ActionElementComponent element={
        <AdvancedButton icon='Hash'  {...actionsInMenuAdditional} >
          Добавить хештег
        </AdvancedButton>} />
    },
    {
      element: <ActionElementComponent element={
        <DatePicker setTaskDate={changeEndDate} end_date={cardData.end_date} side='right' >
          <AdvancedButton icon='Time' {...actionsInMenuAdditional}>
            Дата
          </AdvancedButton>
        </DatePicker>}
      />
    },
    {
      element: <ActionElementComponent element={
        <AdvancedButton icon='Plus' onClick={() => {
          setNewTaskCard(true)
        }} {...actionsInMenuAdditional} >
          Добавить подзадачу
        </AdvancedButton>} />,
    },
    {
      element: <ActionElementComponent element={
        <AdvancedButton icon='Trash' onClick={() => {
          setRemoveTask(true)
        }} {...actionsInMenuAdditional} >
          Удалить
        </AdvancedButton>} />,
      showActionMenu: true
    },
  ];

  useEffect(() => {
    if (newTaskCard) {
      setToggleShow(true);
    }
  }, [newTaskCard]);

  return {
    data,
    showComments,
    setShowComments,
    isEdit,
    setIsEdit,
    taskName,
    sendFiles,
    toggleShow,
    setToggleShow,
    handleToggle,
    handleEditableTaskName,
    taskNameSave,
    enterKeyDown,
    taskCardOptions,
    actionInMenuWrappers,
    newTaskCard,
    setNewTaskCard,
    taskCardOptionsAdditional,
    removeTaskCard,
    removeTask,
    setRemoveTask,
    updateTaskPriority,
    updateTaskPinned,
    updateTaskIsClosed,
  };
};
